/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.util;

import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import com.xuexiang.xui_lib.util.LogUtils;
import com.xuexiang.xuidemo.ResourceTable;

import java.io.IOException;


/**
 * SnackBarUtils
 */
public final class SnackBarUtils extends DirectionalLayout {
    private int mDuration;
    private int cornerRadius;
    private Color backgroundColor;
    private Color strokeColor;
    private int strokeWidth;
    private int iconStart;
    private int iconEnd;
    private Color textColor;
    private Color actionColor;
    private int textAlignment = TextAlignment.LEFT;
    private int textSize;
    private boolean isTextSizeFromStyleXml = false;
    private boolean solidBackground;
//    private boolean textBold;
    private String textMsg, mBt_Action;
    private int gravity;
    private Text textView, btn_action;
    private Image mIvIcon;
    private Component rootLayout;
    private ShapeElement mBackgroundDrawable;
    private int mCornerRadius = 0;
    private PopupDialog popupDialog;
    private int icon;
    private AnimatorProperty property;

    private SnackBarUtils(Context context) {
        super(context);
    }

    /**
     * 显示
     */
    public void show() {
        System.out.println("=====setDuration==进来了========>");
        rootLayout = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_popup_layout, null, true);
        textView = (Text) rootLayout.findComponentById(ResourceTable.Id_textview);
        btn_action = (Text) rootLayout.findComponentById(ResourceTable.Id_btn_action);
        mIvIcon = (Image) rootLayout.findComponentById(ResourceTable.Id_iv_icon);
        setLayoutBackground();
        setTextView();
        setIcon();

        popupDialog = new PopupDialog(mContext, null);
        popupDialog.setCustomComponent(rootLayout);
        property = createAnimBOTTOM();
        popupDialog.setSize(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_CONTENT);
        popupDialog.setTransparent(true);
        //  popupDialog.setAlignment(gravity);
        if (mDuration > 0) {
            System.out.println("=====setDuration==========>");
            popupDialog.setDuration(mDuration);
            popupDialog.setAutoClosable(true);
        } else {
            popupDialog.setAutoClosable(false);
            System.out.println("=====setDuration========setAutoClosable==>");
        }
        popupDialog.showOnCertainPosition(gravity, 0, 100);
        property.setTarget(rootLayout);
        property.start();
    }

    private AnimatorProperty createAnimBOTTOM() {
        AnimatorProperty animator = new AnimatorProperty();
        animator.moveFromY(200).moveToY(0).alphaFrom(0).alpha(1).setDuration(200);
        return animator;
    }

    /**
     * 设置前后图片
     */
    private void setIcon() {
        int top = (int) AttrHelper.fp2px(0, getContext());
        //paddingNoIcon
        int left = (int) AttrHelper.fp2px(10, getContext());
        //paddingHorizontal1
        int right = (int) AttrHelper.fp2px(10, getContext());
        int iconSize = (int) AttrHelper.fp2px(20, getContext());

        if (iconStart != 0) {
            try {
                Resource resource = getContext().getResourceManager().getResource(iconStart);
                PixelMapElement drawable = new PixelMapElement(resource);
                if (drawable != null) {
                    drawable.setBounds(0, 0, iconSize, iconSize);
                    textView.setAroundElementsRelative(drawable, null, null, null);
                    if (isRTL()) {
                        rootLayout.setPadding(left, top, right, top);
                    } else {
                        rootLayout.setPadding(right, top, left, top);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NotExistException e) {
                e.printStackTrace();
            }
        }

        if (iconEnd != 0) {
            Resource resource = null;
            try {
                resource = getContext().getResourceManager().getResource(iconEnd);
                PixelMapElement drawable = new PixelMapElement(resource);
                if (drawable != null) {
                    drawable.setBounds(0, 0, iconSize, iconSize);
                    textView.setAroundElementsRelative(null, null, drawable, null);
                    if (isRTL()) {
                        rootLayout.setPadding(left, top, left, top);
                    } else {
                        rootLayout.setPadding(left, top, right, top);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NotExistException e) {
                e.printStackTrace();
            }

        }

        if (iconStart != 0 && iconEnd != 0) {

            try {
                Resource resource_left = getContext().getResourceManager().getResource(iconStart);
                PixelMapElement drawableLeft = new PixelMapElement(resource_left);
                Resource resource_right = getContext().getResourceManager().getResource(iconEnd);
                PixelMapElement drawableRight = new PixelMapElement(resource_right);
                if (drawableLeft != null && drawableRight != null) {
                    drawableLeft.setBounds(0, 0, iconSize, iconSize);
                    drawableRight.setBounds(0, 0, iconSize, iconSize);
                    textView.setAroundElements(drawableLeft, null, drawableRight, null);
                    textView.setPaddingRelative(10, 20, 450, 20);
                    rootLayout.setPadding(right, top, right, top);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (NotExistException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 获取是否RTL的布尔值
     *
     * @return boolean
     */
    static boolean isRTL() {
        return true;
    }

    /**
     * 设置文本样式
     */
    private void setTextView() {
        LogUtils.info("setTextView", "setTextView==" + textMsg);
        textView.setText(textMsg);
        setmIvIcon();
        if (textColor != null) {
            textView.setTextColor(textColor);
        }
        if (textSize > 0) {
            textView.setTextSize(textSize, isTextSizeFromStyleXml ? Text.TextSizeType.PX : Text.TextSizeType.VP);
        }
        if (textAlignment > 0) {
            mContext.getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    textView.setTextAlignment(textAlignment);
                }
            });
        }
        if (!TextUtils.isEmpty(mBt_Action)) {
            btn_action.setVisibility(Component.VISIBLE);
            btn_action.setText(mBt_Action);
            if (actionColor != null) {
                btn_action.setTextColor(actionColor);
            }
            setmBtnActionWithIconListener();
        }
    }

    /**
     * 设置图片
     */
    public void setmIvIcon() {
        LogUtils.info("setmIvIcon", "setmIvIcon==" + icon);
        if (icon != 0) {
            mIvIcon.setVisibility(Component.VISIBLE);
            mIvIcon.setPixelMap(icon);
        }
    }

    /**
     * 设置按钮监听
     *
     * @param
     */
    public void setmBtnActionWithIconListener() {
        btn_action.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                ToastUtil.showToast(mContext, "点击了" + mBt_Action + "!");
                if (popupDialog.isShowing()) {
                    popupDialog.destroy();
                }
            }
        });
    }


    /**
     * 设置PopupDialog背景
     */

    private void setLayoutBackground() {
        mBackgroundDrawable = new ShapeElement();
        mBackgroundDrawable.setAlpha(230);
        //默认是30 但是 rootLayout.setBackground(mBackgroundDrawable);调用了该方法  backgrund中的shape图形设置的 radius就失效了
        mBackgroundDrawable.setCornerRadius(AttrHelper.fp2px(mCornerRadius, getContext()));
        if (strokeWidth > 0) {
            mBackgroundDrawable.setStroke(AttrHelper.fp2px(strokeWidth, getContext()), RgbColor.fromArgbInt(strokeColor.getValue()));
        }
        if (cornerRadius > -1) {
            mBackgroundDrawable.setCornerRadius(AttrHelper.fp2px(cornerRadius, getContext()));
        }
        if (backgroundColor != null) {
            mBackgroundDrawable.setRgbColor(RgbColor.fromArgbInt(backgroundColor.getValue()));
        }
        if (solidBackground) {
            mBackgroundDrawable.setAlpha(255);
        }
        rootLayout.setBackground(mBackgroundDrawable);
    }


    /**
     * 获取构建者
     *
     * @param context
     * @return Builder构造者对象
     */
    public static Builder builder(Context context) {
        return new Builder(context);
    }

    private SnackBarUtils(Builder builder) {
        super(builder.context);
        this.backgroundColor = builder.params.backgroundColor;
        this.cornerRadius = builder.params.cornerRadius;
        this.mDuration = builder.params.mDuration;
        this.iconEnd = builder.params.iconEnd;
        this.iconStart = builder.params.iconStart;
        this.strokeColor = builder.params.strokeColor;
        this.strokeWidth = builder.params.strokeWidth;
        this.solidBackground = builder.params.solidBackground;
        this.textColor = builder.params.textColor;
        this.textColor = builder.params.textColor;
        this.textSize = builder.params.textSize;
//        this.textBold = builder.params.textBold;
        this.textAlignment = builder.params.textAlignment;
        this.actionColor = builder.params.actionColor;
        this.textMsg = builder.params.textMsg;
        this.mBt_Action = builder.params.mBt_Action;
        this.gravity = builder.params.gravity;
        this.icon = builder.params.icon;
    }

    final static class Params {
        /**
         * 圆角
         */
        public int cornerRadius = -1;
        /**
         * 持续时间
         */
        public int mDuration = 2000;
        /**
         * 背景颜色
         */
        public Color backgroundColor;
        /**
         * 胶囊边颜色
         */
        public Color strokeColor;
        /**
         * 胶囊边宽度
         */
        public int strokeWidth;
        /**
         * 图标起点
         */
        public int iconStart;
        /**
         * 图标终点
         */
        public int iconEnd;
        /**
         * 图标字体颜色
         */
        public Color textColor;
        /**
         * 字体居中显示类型
         */
        public int textAlignment;
        /**
         * 字符长度
         */
        public int length;
        /**
         * 字体大小
         */
        public int textSize;
        /**
         * 主体区域的背景
         */
        public boolean solidBackground;
        /**
         * 字体样式
         */
        public boolean textBold;
        /**
         * 显示字符
         */
        public String textMsg;
        /**
         * 居中判定
         */
        public int gravity = LayoutAlignment.CENTER;
        /**
         * int图标
         */
        public int icon;
        /**
         * 按钮动作
         */
        public String mBt_Action;
        /**
         * 按钮动作之后颜色
         */
        public Color actionColor;

    }

    /**
     * 构造基类
     */
    public static class Builder {

        private Params params = new Params();
        /**
         * 上下文
         */
        public final Context context;

        /**
         * 构造器
         *
         * @param context
         */
        public Builder(Context context) {
            this.context = context;
        }

        /**
         * 设置字体显示信息
         *
         * @param textMsg
         * @return Builder对象
         */
        public Builder textMsg(String textMsg) {
            this.params.textMsg = textMsg;
            return this;
        }

        /**
         * 设置字体颜色
         *
         * @param textColor
         * @return Builder对象
         */
        public Builder textColor(Color textColor) {
            this.params.textColor = textColor;
            return this;
        }

        /**
         * 设置字体样式
         *
         * @return Builder对象
         */
        public Builder textBold() {
            this.params.textBold = true;
            return this;
        }

        /**
         * 设置字体大小
         *
         * @param textSize
         * @return Builder对象
         */
        public Builder textSize(int textSize) {
            this.params.textSize = textSize;
            return this;
        }

        /**
         * textAlignment
         *
         * @param textAlignment A font resource id like R.font.somefont as introduced with the new font api
         * @return return
         */
        public Builder textAlignment(int textAlignment) {
            this.params.textAlignment = textAlignment;
            return this;
        }

        /**
         * 设置背景颜色
         *
         * @param backgroundColor backgroundColor
         * @return Builder对象
         */
        public Builder backgroundColor(Color backgroundColor) {
            this.params.backgroundColor = backgroundColor;
            return this;
        }

        /**
         * This call will make the StyleablePopupDialog's background completely solid without any opacity.
         *
         * @return return
         */
        public Builder solidBackground() {
            this.params.solidBackground = true;
            return this;
        }

        /**
         * 设置胶囊边
         *
         * @param strokeWidth
         * @param strokeColor
         * @return Builder对象
         */
        public Builder stroke(int strokeWidth, Color strokeColor) {
            this.params.strokeWidth = strokeWidth;
            this.params.strokeColor = strokeColor;
            return this;
        }

        /**
         * mDuration
         *
         * @param mDuration Sets the corner radius of the StyleablePopupDialog's shape.
         * @return return
         */
        public Builder mDuration(int mDuration) {
            this.params.mDuration = mDuration;
            return this;
        }

        /**
         * 设置圆角大小
         *
         * @param cornerRadius
         * @return Builder对象
         */
        public Builder cornerRadius(int cornerRadius) {
            this.params.cornerRadius = cornerRadius;
            return this;
        }

        /**
         * 设置开始处的图标
         *
         * @param iconStart
         * @return Builder对象
         */
        public Builder iconStart(int iconStart) {
            this.params.iconStart = iconStart;
            return this;
        }

        /**
         * 设置结束处图标
         *
         * @param iconEnd
         * @return Builder对象
         */
        public Builder iconEnd(int iconEnd) {
            this.params.iconEnd = iconEnd;
            return this;
        }

        /**
         * 设置图标
         *
         * @param icon
         * @return Builder对象
         */
        public Builder icon(int icon) {
            this.params.icon = icon;
            return this;
        }

        /**
         * Sets where the StyleablePopupDialog will appear on the screen
         *
         * @param gravity gravity
         * @return return
         */
        public Builder gravity(int gravity) {
            this.params.gravity = gravity;
            return this;
        }

        /**
         * button的动作设置
         *
         * @param mBt_Action
         * @return Builder对象
         */
        public Builder mBt_Action(String mBt_Action) {
            this.params.mBt_Action = mBt_Action;
            return this;
        }

        /**
         * button跟随动作的颜色设置
         *
         * @param actionColor
         * @return Builder对象
         */
        public Builder actionColor(Color actionColor) {
            this.params.actionColor = actionColor;
            return this;
        }

        /**
         * 字体的length
         *
         * @param length
         * @return Builder对象
         */
        public Builder length(int length) {
            this.params.length = length;
            return this;
        }

        /**
         * show方法调用
         */
        public void show() {
            new SnackBarUtils(this).show();
        }
    }

    /**
     * 展示SnackBar
     *
     * @param context context
     * @param textMsg 文本内容
     * @param backgroundColor backgroundColor
     * @param startIcon 左边加载图片
     * @param endIcon 右边加载图片
     */
    public static void show(Context context, String textMsg, Color backgroundColor, int startIcon, int endIcon) {
        SnackBarUtils.builder(context)
            .textMsg(textMsg)
            .backgroundColor(backgroundColor)
            .solidBackground()
            .gravity(LayoutAlignment.BOTTOM)
            .textAlignment(TextAlignment.LEFT)
            .textColor(Color.WHITE)
            .textBold()
            .iconStart(startIcon)
            .iconEnd(endIcon)
            .show();
    }

    /**
     * 展示SnackBar
     *
     * @param context 上下文
     * @param textMsg 文本内容
     * @param startIcon 左边加载图片
     * @param endIcon 右边加载图片
     */
    public static void show(Context context, String textMsg, int startIcon, int endIcon) {
        SnackBarUtils.builder(context)
            .textMsg(textMsg)
            .backgroundColor(new Color(AppCfig.h_black))
            .solidBackground()
            .textColor(Color.WHITE)
            .textBold()
            .cornerRadius(40)
            .textSize(12)
            .iconStart(startIcon)
            .iconEnd(endIcon)
            .show();
    }

    /**
     * 展示SnackBar
     *
     * @param context
     * @param textMsg
     * @param icon
     */
    public static void show(Context context, String textMsg, int icon) {
        SnackBarUtils.builder(context)
            .textMsg(textMsg)
            .backgroundColor(Color.BLACK)
            .solidBackground()
            .gravity(LayoutAlignment.BOTTOM)
            .textColor(Color.WHITE)
            .textBold()
            .textSize(12)
            .icon(icon)
            .show();
    }

    /**
     * 展示SnackBar
     *
     * @param context 上下文
     * @param backgroundColor backgroundColor
     * @param alignment alignment
     * @param textAlignment textAlignment
     * @param textMsg 文本内容
     */
    public static void show(Context context, Color backgroundColor, int alignment, int textAlignment, String textMsg) {
        SnackBarUtils.builder(context)
            .gravity(alignment)
            .textMsg(textMsg)
            .textAlignment(textAlignment)
            .backgroundColor(backgroundColor)
            .solidBackground()
            .textColor(Color.WHITE)
            .textBold()
            .cornerRadius(40)
            .textSize(12)
            .stroke(2, new Color(AppCfig.SOLID))
            .show();
    }

    /**
     * 展示SnackBar
     *
     * @param context 上下文
     * @param backgroundColor 背景样式
     * @param textColor 文本颜色
     * @param actionColor 按钮颜色
     * @param mDuration 设置时间
     * @param textAlignment 文本位置
     * @param gravity 布局位置
     * @param textMsg 文本内容
     * @param mBt_Action 按钮内容
     */
    public static void show(Context context, Color backgroundColor, Color textColor, Color actionColor, int mDuration,
                            int gravity, int textAlignment, String textMsg, String mBt_Action) {
        SnackBarUtils.builder(context)
            .gravity(gravity)
            .textMsg(textMsg)
            .backgroundColor(backgroundColor)
            .solidBackground()
            .textColor(textColor)
            .mBt_Action(mBt_Action)
            .actionColor(actionColor)
            .textAlignment(textAlignment)
            .mDuration(mDuration)
            .show();
    }
}
